<template>
  <PageWrapper title="" contentBackground contentClass="p-4">
    <Row :gutter="[16, 16]">
      <Col :span="8">
        <div class="weixin-preview">
          <div class="weixin-hd">
            <div class="weixin-title">{{ state.weixinTitle }}</div>
          </div>
          <div class="weixin-bd">
            <ul class="weixin-menu" id="weixin-menu">
              <li
                v-for="(btn, i) in state.menu.buttons"
                class="menu-item"
                :class="{ current: state.selectedMenuIndex === i && selectedMenuLevel() == 1 }"
                @click="selectedMenu(i, $event)"
                :key="i"
              >
                <div class="menu-item-title">
                  <i class="icon_menu_dot"></i>
                  <span>{{ btn.name }}</span>
                </div>
                <ul class="weixin-sub-menu" v-show="state.selectedMenuIndex === i">
                  <li
                    v-for="(sub, i2) in btn.subButtons"
                    class="menu-sub-item"
                    :class="{ current: state.selectedSubMenuIndex === i2 && selectedMenuLevel() == 2 }"
                    @click.stop="selectedSubMenu(i2, $event)"
                    :key="i2"
                  >
                    <div class="menu-item-title">
                      <span>{{ sub.name }}</span>
                    </div>
                  </li>
                  <li v-if="btn.subButtons.length < 5" class="menu-sub-item" @click.stop="addMenu(2)">
                    <div class="menu-item-title">
                      <i class="icon14_menu_add"></i>
                    </div>
                  </li>
                  <i class="menu-arrow arrow_out"></i>
                  <i class="menu-arrow arrow_in"></i>
                </ul>
              </li>
              <template v-if="state.menu.buttons.length < 3">
                <li class="menu-item" @click="addMenu(1)"> <i class="icon14_menu_add"></i></li>
              </template>
            </ul>
          </div>
        </div>
      </Col>
      <Col :span="8">
        <!-- 主菜单 -->
        <div class="weixin-menu-detail" v-if="selectedMenuLevel() == 1">
          <div class="menu-input-group" style="border-bottom: 2px #e8e8e8 solid">
            <div class="menu-name">{{ state.menu.buttons[state.selectedMenuIndex].name }}</div>
            <div class="menu-del" @click="delMenu">删除菜单</div>
          </div>
          <div class="menu-input-group">
            <div class="menu-label">菜单名称</div>
            <div class="menu-input">
              <Input
                type="text"
                name="name"
                placeholder="请输入菜单名称"
                class="menu-input-text"
                v-model:value="state.menu.buttons[state.selectedMenuIndex].name"
                @input="checkMenuName(state.menu.buttons[state.selectedMenuIndex].name)"
              />
              <p class="menu-tips" style="color: #e15f63" v-show="state.menuNameBounds">字数超过上限</p>
              <p class="menu-tips">字数不超过4个汉字或8个字母</p>
            </div>
          </div>
          <template v-if="state.menu.buttons[state.selectedMenuIndex].subButtons.length == 0">
            <div class="menu-input-group">
              <div class="menu-label">菜单内容</div>
              <div class="menu-input">
                <Select
                  :options="getMenuTypeOptions"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].type"
                  name="type"
                  class="menu-input-text"
                />
              </div>
            </div>
            <div class="menu-content" v-if="selectedMenuType() == 1">
              <div class="menu-input-group">
                <p class="menu-tips">订阅者点击该子菜单会跳到以下链接</p>
                <div class="menu-label">页面地址</div>
                <div class="menu-input">
                  <Input type="text" placeholder="" class="menu-input-text" v-model:value="state.menu.buttons[state.selectedMenuIndex].url" />
                  <p class="menu-tips cursor" @click="selectNewsUrl">从公众号图文消息中选择</p>
                </div>
              </div>
            </div>
            <div class="menu-msg-content" v-else-if="selectedMenuType() == 2" v-loading="state.materialLoading">
              <div class="menu-msg-head"><i class="icon_msg_sender"></i>图文消息</div>
              <div class="menu-msg-panel" v-if="state.menu.buttons[state.selectedMenuIndex].media_id">
                <div class="menu-msg-select">
                  <div class="menu-msg-title"><i class="icon_msg_sender"></i>{{ state.material.title }}</div>
                  <a :href="material.url" target="_blank" class="el-button el-button--mini">查看</a>
                  <a-button size="mini" type="danger" @click="delMaterialId">删除</a-button>
                </div>
              </div>
              <div class="menu-msg-panel" v-else>
                <div class="menu-msg-select" @click="selectMaterialId">
                  <i class="icon36_common add_gray"></i>
                  <strong>从素材库中选择</strong>
                </div>
              </div>
            </div>
            <div class="menu-content" v-else-if="selectedMenuType() == 3">
              <div class="menu-input-group">
                <p class="menu-tips">用于消息接口推送，不超过128字节</p>
                <div class="menu-label">菜单KEY值</div>
                <div class="menu-input">
                  <Input type="text" placeholder="" class="menu-input-text" v-model:value="state.menu.buttons[state.selectedMenuIndex].key" />
                </div>
              </div>
            </div>
            <div class="menu-content" v-else-if="selectedMenuType() == 4">
              <div class="menu-input-group">
                <p class="menu-tips">订阅者点击该子菜单会跳到以下小程序</p>
                <div class="menu-label">小程序APPID</div>
                <div class="menu-input">
                  <Input
                    type="text"
                    placeholder="小程序的appid（仅认证公众号可配置）"
                    class="menu-input-text"
                    v-model:value="state.menu.buttons[state.selectedMenuIndex].appid"
                  />
                </div>
              </div>
              <div class="menu-input-group">
                <div class="menu-label">小程序路径</div>
                <div class="menu-input">
                  <Input
                    type="text"
                    placeholder="小程序的页面路径 pages/Index/index"
                    class="menu-input-text"
                    v-model:value="state.menu.buttons[state.selectedMenuIndex].pagepath"
                  />
                </div>
              </div>
              <div class="menu-input-group">
                <div class="menu-label">备用网页</div>
                <div class="menu-input">
                  <Input type="text" placeholder="" class="menu-input-text" v-model:value="state.menu.buttons[state.selectedMenuIndex].url" />
                  <p class="menu-tips">旧版微信客户端无法支持小程序，用户点击菜单时将会打开备用网页。</p>
                </div>
              </div>
            </div>
          </template>
        </div>
        <!-- 子菜单 -->
        <div class="weixin-menu-detail" v-if="selectedMenuLevel() == 2">
          <div class="menu-input-group" style="border-bottom: 2px #e8e8e8 solid">
            <div class="menu-name">{{ state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].name }}</div>
            <div class="menu-del" @click="delMenu">删除子菜单</div>
          </div>
          <div class="menu-input-group">
            <div class="menu-label">子菜单名称</div>
            <div class="menu-input">
              <Input
                type="text"
                placeholder="请输入子菜单名称"
                class="menu-input-text"
                v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].name"
                @input="checkMenuName(state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].name)"
              />
              <p class="menu-tips" style="color: #e15f63" v-show="state.menuNameBounds">字数超过上限</p>
              <p class="menu-tips">字数不超过8个汉字或16个字母</p>
            </div>
          </div>
          <div class="menu-input-group">
            <div class="menu-label">子菜单内容</div>
            <div class="menu-input">
              <Select
                :options="getMenuTypeOptions"
                v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].type"
                name="type"
                class="menu-input-text"
              />
            </div>
          </div>
          <div class="menu-content" v-if="selectedMenuType() == 1">
            <div class="menu-input-group">
              <p class="menu-tips">订阅者点击该子菜单会跳到以下链接</p>
              <div class="menu-label">页面地址</div>
              <div class="menu-input">
                <Input
                  type="text"
                  placeholder=""
                  class="menu-input-text"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].url"
                />
                <p class="menu-tips cursor" @click="selectNewsUrl">从公众号图文消息中选择</p>
              </div>
            </div>
          </div>
          <div class="menu-msg-content" v-else-if="selectedMenuType() == 2" v-loading="state.materialLoading">
            <div class="menu-msg-head"><i class="icon_msg_sender"></i>图文消息</div>
            <div class="menu-msg-panel" v-if="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].media_id">
              <div class="menu-msg-select">
                <i class="icon_msg_sender"></i>
                <span>{{ state.material.title }}</span>
                <a :href="state.material.url" target="_blank" class="el-button el-button--mini">查看</a>
                <a-button size="mini" type="danger" @click="delMaterialId">删除</a-button>
              </div>
            </div>
            <div class="menu-msg-panel" v-else>
              <div class="menu-msg-select" @click="selectMaterialId">
                <i class="icon36_common add_gray"></i>
                <strong>从素材库中选择</strong>
              </div>
            </div>
          </div>
          <div class="menu-content" v-else-if="selectedMenuType() == 3">
            <div class="menu-input-group">
              <p class="menu-tips">用于消息接口推送，不超过128字节</p>
              <div class="menu-label">菜单KEY值</div>
              <div class="menu-input">
                <Input
                  type="text"
                  placeholder=""
                  class="menu-input-text"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].key"
                />
              </div>
            </div>
          </div>
          <div class="menu-content" v-else-if="selectedMenuType() == 4">
            <div class="menu-input-group">
              <p class="menu-tips">订阅者点击该子菜单会跳到以下小程序</p>
              <div class="menu-label">小程序APPID</div>
              <div class="menu-input">
                <Input
                  type="text"
                  placeholder="小程序的appid（仅认证公众号可配置）"
                  class="menu-input-text"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].appid"
                />
              </div>
            </div>
            <div class="menu-input-group">
              <div class="menu-label">小程序路径</div>
              <div class="menu-input">
                <Input
                  type="text"
                  placeholder="小程序的页面路径 pages/Index/index"
                  class="menu-input-text"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].pagepath"
                />
              </div>
            </div>
            <div class="menu-input-group">
              <div class="menu-label">备用网页</div>
              <div class="menu-input">
                <Input
                  type="text"
                  placeholder=""
                  class="menu-input-text"
                  v-model:value="state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].url"
                />
                <p class="menu-tips">旧版微信客户端无法支持小程序，用户点击菜单时将会打开备用网页。</p>
              </div>
            </div>
          </div>
        </div>
      </Col>
    </Row>
    <Row>
      <div class="weixin-btn-group">
        <Button type="primary" @click="onMenuSubmit">发布</Button>
        <Button type="danger" @click="onMenuClear">清空</Button>
      </div>
    </Row>
  </PageWrapper>

  <MaterialSelectModal @register="registerMaterialModal" @getSelectResult="setMaterialId" :appid="state.weixinAppId" />
  <NewsSelectModal @register="registerNewsModal" @getSelectResult="setNewsUrl" :appid="state.weixinAppId" />
</template>
<script lang="ts">
  import { reactive, onMounted } from 'vue';
  import { Select, Input, Button } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { Row, Col } from 'ant-design-vue';
  // import { vuedraggable } from 'vuedraggable';
  import { MenuButton, menuButtonTypes, MenuButtonType } from './mp.data';
  import { createMenu, getMenuDetail, deleteMenu, deleteMenuByMenuId, getMaterialInfo } from './mp.api';
  import MaterialSelectModal from './MaterialSelectModal.vue';
  import NewsSelectModal from './NewsSelectModal.vue';

  export default {
    name: 'WeixinMpMenu',
    components: {
      PageWrapper,
      Row,
      Col,
      Select,
      Input,
      Button,
      MaterialSelectModal,
      NewsSelectModal,
      // vuedraggable,
    },
    setup() {
      const { createMessage, createConfirm, createSuccessModal, createInfoModal, createErrorModal, createWarningModal, notification } = useMessage();

      const [registerMaterialModal, materialModal] = useModal();
      const [registerNewsModal, newsModal] = useModal();

      const state = reactive({
        weixinTitle: 'Vue.js公众号菜单',
        weixinAppId: 'wx79ccef2ace94b547',
        menu: { buttons: [] as Array<MenuButton> }, //当前菜单
        selectedMenuIndex: '' as any, //当前选中菜单索引
        selectedSubMenuIndex: '' as any, //当前选中子菜单索引
        menuNameBounds: false, //菜单长度是否过长
        material: {
          title: '',
          url: '',
          thumb_url: '',
        },
      });

      const getMenuTypeOptions = menuButtonTypes.map((item) => ({
        label: item.name,
        value: item.type,
        key: item.type,
      }));

      onMounted(() => {
        getMenu();
      });

      async function getMenu() {
        try {
          let { menu } = await getMenuDetail(state.weixinAppId);
          state.menu = menu;
        } catch (err) {
          console.error(err);
          createMessage.error('获得微信公众号菜单异常');
        }
      }

      //选中主菜单
      function selectedMenu(i, event) {
        state.selectedSubMenuIndex = '';
        state.selectedMenuIndex = i;
        let selectedMenu = state.menu.buttons[state.selectedMenuIndex];
        //清空选中media_id 防止再次请求
        if (selectedMenu.media_id && selectedMenuType() == 2) {
          getMaterial(selectedMenu.media_id);
        }
        //检查名称长度
        checkMenuName(selectedMenu.name);
      }

      //选中子菜单
      function selectedSubMenu(i, event) {
        state.selectedSubMenuIndex = i;
        let selectedSubMenu = state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex];
        if (selectedSubMenu.media_id && selectedMenuType() == 2) {
          getMaterial(selectedSubMenu.media_id);
        }
        checkMenuName(selectedSubMenu.name);
      }

      //选中菜单级别
      function selectedMenuLevel() {
        if (state.selectedMenuIndex !== '' && state.selectedSubMenuIndex === '') {
          //主菜单
          return 1;
        } else if (state.selectedMenuIndex !== '' && state.selectedSubMenuIndex !== '') {
          //子菜单
          return 2;
        } else {
          //未选中任何菜单
          return 0;
        }
      }

      //获取菜单类型 1. view网页类型，2. media_id类型和view_limited类型 3. click点击类型，4.miniprogram表示小程序类型
      function selectedMenuType() {
        if (selectedMenuLevel() == 1 && state.menu.buttons[state.selectedMenuIndex].subButtons.length == 0) {
          //主菜单
          const selectedMenuButtonType = menuButtonTypes.find((item) => {
            return item.type == state.menu.buttons[state.selectedMenuIndex].type;
          }) as MenuButtonType;
          return selectedMenuButtonType.value;
        } else if (selectedMenuLevel() == 2) {
          //子菜单
          const selectedMenuButtonType = menuButtonTypes.find((item) => {
            return item.type == state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].type;
          }) as MenuButtonType;
          return selectedMenuButtonType.value;
        } else {
          return 1;
        }
      }

      //添加菜单
      function addMenu(level) {
        if (level == 1 && state.menu.buttons.length < 3) {
          state.menu.buttons.push({
            type: 'view',
            name: '菜单名称',
            subButtons: [] as Array<MenuButton>,
            url: '',
          });
          state.selectedMenuIndex = state.menu.buttons.length - 1;
          state.selectedSubMenuIndex = '';
        }
        if (level == 2 && state.menu.buttons[state.selectedMenuIndex].subButtons.length < 5) {
          state.menu.buttons[state.selectedMenuIndex].subButtons.push({
            type: 'view',
            name: '子菜单名称',
            subButtons: [] as Array<MenuButton>,
            url: '',
          });
          state.selectedSubMenuIndex = state.menu.buttons[state.selectedMenuIndex].subButtons.length - 1;
        }
      }

      //删除菜单
      async function delMenu() {
        if (selectedMenuLevel() == 1) {
          try {
            createConfirm({
              title: '提示',
              content: '删除后菜单下设置的内容将被删除',
              iconType: 'warning',
              onOk: () => {
                if (state.selectedMenuIndex === 0) {
                  state.menu.buttons.splice(state.selectedMenuIndex, 1);
                  state.selectedMenuIndex = 0;
                } else {
                  state.menu.buttons.splice(state.selectedMenuIndex, 1);
                  state.selectedMenuIndex -= 1;
                }
                if (state.menu.buttons.length == 0) {
                  state.selectedMenuIndex = '';
                }
              },
              onCancel: () => {},
            });
          } catch {
            return;
          }
        } else if (selectedMenuLevel() == 2) {
          if (state.selectedSubMenuIndex === 0) {
            state.menu.buttons[state.selectedMenuIndex].subButtons.splice(state.selectedSubMenuIndex, 1);
            state.selectedSubMenuIndex = 0;
          } else {
            state.menu.buttons[state.selectedMenuIndex].subButtons.splice(state.selectedSubMenuIndex, 1);
            state.selectedSubMenuIndex -= 1;
          }
          if (state.menu.buttons[state.selectedMenuIndex].subButtons.length == 0) {
            state.selectedSubMenuIndex = '';
          }
        }
      }

      //检查菜单名称长度
      function checkMenuName(val) {
        if (selectedMenuLevel() == 1 && getMenuNameLen(val) <= 8) {
          state.menuNameBounds = false;
        } else if (selectedMenuLevel() == 2 && getMenuNameLen(val) <= 16) {
          state.menuNameBounds = false;
        } else {
          state.menuNameBounds = true;
        }
      }

      //获取菜单名称长度
      function getMenuNameLen(val) {
        var len = 0;
        for (var i = 0; i < val.length; i++) {
          var a = val.charAt(i);
          a.match(/[^\x00-\xff]/gi) != null ? (len += 2) : (len += 1);
        }
        return len;
      }

      //选择公众号素材库素材
      function selectMaterialId() {
        materialModal.openModal(true, {
          title: '选择公众号素材库素材模板',
          isUpdate: false,
          record: {},
        });
      }

      //选择公众号图文链接
      function selectNewsUrl() {
        newsModal.openModal(true, {
          title: '选择公众号图文链接模板',
          isUpdate: false,
          record: {},
        });
      }

      //设置选择的素材id
      function setMaterialId(options, values) {
        let { media_id, content } = values;
        if (selectedMenuLevel() == 1) {
          //this.$set(this.menu.buttons[this.selectedMenuIndex],'media_id',media_id);
          state.menu.buttons[state.selectedMenuIndex].media_id = media_id;
        } else if (selectedMenuLevel() == 2) {
          //this.$set(this.menu.buttons[this.selectedMenuIndex].subButtons[this.selectedSubMenuIndex],'media_id',media_id);
          state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].media_id = media_id;
        }
        let { articles } = content;
        let item = articles[0];
        state.material.title = item.title;
        state.material.url = item.url;
      }

      //删除选择的素材id
      function delMaterialId() {
        if (selectedMenuLevel() == 1) {
          //this.$set(this.menu.buttons[this.selectedMenuIndex],'media_id','');
          state.menu.buttons[state.selectedMenuIndex].media_id = '';
        } else if (selectedMenuLevel() == 2) {
          //this.$set(this.menu.buttons[this.selectedMenuIndex].subButtons[this.selectedSubMenuIndex],'media_id','');
          state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].media_id = '';
        }
      }

      //设置选择的图文链接
      function setNewsUrl(options, values) {
        let { url } = values;
        if (selectedMenuLevel() == 1) {
          //this.$set(this.menu.buttons[this.selectedMenuIndex], 'url', url);
          state.menu.buttons[state.selectedMenuIndex].url = url;
        } else if (selectedMenuLevel() == 2) {
          //this.$set(state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex], 'url', url);
          state.menu.buttons[state.selectedMenuIndex].subButtons[state.selectedSubMenuIndex].url = url;
        }
      }

      //获取素材信息
      async function getMaterial(id) {
        try {
          const { articles } = await getMaterialInfo({ params: { appid: state.weixinAppId, mediaId: id } });
          state.material.title = articles[0].title;
          state.material.url = articles[0].url;
        } catch (err) {
          console.error(err);
        }
      }

      async function onMenuSubmit() {
        try {
          createConfirm({
            title: '提示',
            content: '确定后发布当前自定义菜单',
            iconType: 'warning',
            onOk: async () => {
              console.log(JSON.stringify(state.menu));
              const { success, msg } = await createMenu(state.weixinAppId, state.menu);
              if (success) {
                createMessage.success('发布成功');
              } else {
                createMessage.error(msg);
              }
            },
            onCancel: () => {},
          });
        } catch (err) {
          console.error(err);
        }
      }

      async function onMenuClear() {
        try {
          createConfirm({
            title: '提示',
            content: '确定后将清空后公众号自定义菜单',
            iconType: 'warning',
            onOk: () => {
              state.menu.buttons = [];
              createMessage.success('清空成功');
            },
            onCancel: () => {},
          });
        } catch (err) {
          console.error(err);
        }
      }

      return {
        //...toRefs(state),
        state,
        getMenuTypeOptions,
        selectedMenu,
        selectedSubMenu,
        selectedMenuType,
        selectedMenuLevel,
        addMenu,
        delMenu,
        checkMenuName,
        selectMaterialId,
        selectNewsUrl,
        setMaterialId,
        delMaterialId,
        setNewsUrl,
        onMenuSubmit,
        onMenuClear,
        registerMaterialModal,
        registerNewsModal,
      };
    },
  };
</script>

<style scoped>
  @import '../assets/css/menu.css';
</style>
